package com.credithc.eagleeye.api.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.atomic.AtomicBoolean;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2018年03月09日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@SuppressWarnings("unchecked")
@Slf4j
public class SpringContextUtils {
    private static ApplicationContext applicationContext;
    private static AtomicBoolean initState = new AtomicBoolean(false);
    public static void init(ApplicationContext applicationContext) {
        if (initState.compareAndSet(false, true)) {
            SpringContextUtils.applicationContext = applicationContext;
        }else{
            log.error("重复初始化SpringContextUtils");
        }
    }

    public static <T> T getBean(String beanName) {
        if(applicationContext!=null) {
            return (T) applicationContext.getBean(beanName);
        }
        log.error("SpringContextUtils未被初始化");
        return null;
    }

    public static <T> T getBean(Class<T> requiredType) {
        if(applicationContext!=null) {
            return (T) applicationContext.getBean(requiredType);
        }
        log.error("SpringContextUtils未被初始化");
        return null;
    }
}
